package com.demo.accessibilitykeeper;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import java.lang.reflect.Method;

/**
 * 高级应用隐藏工具类
 * 支持多厂商、多Android版本的全面隐藏策略
 */
public class AdvancedAppHider {
    
    private static final String TAG = "AdvancedAppHider";
    
    private Context context;
    private PackageManager packageManager;
    private String packageName;
    
    public AdvancedAppHider(Context context) {
        this.context = context;
        this.packageManager = context.getPackageManager();
        this.packageName = context.getPackageName();
    }
    
    /**
     * 执行全面的应用隐藏策略
     */
    public void executeComprehensiveHide() {
        try {
            Log.d(TAG, "🚀 STARTING_COMPREHENSIVE_HIDE - Executing advanced app hiding strategy");
            
            // 获取设备信息
            String manufacturer = Build.MANUFACTURER.toLowerCase();
            int sdkVersion = Build.VERSION.SDK_INT;
            
            Log.d(TAG, "📱 DEVICE_INFO - Manufacturer: " + manufacturer + ", Android API: " + sdkVersion);
            
            boolean hideSuccess = false;
            
            // 根据厂商选择最佳隐藏策略
            if (isHuaweiDevice(manufacturer)) {
                hideSuccess |= hideForHuawei();
            } else if (isSamsungDevice(manufacturer)) {
                hideSuccess |= hideForSamsung();
            } else if (isXiaomiDevice(manufacturer)) {
                hideSuccess |= hideForXiaomi();
            } else if (isOppoVivoDevice(manufacturer)) {
                hideSuccess |= hideForOppoVivo();
            }
            
            // 通用方法1：标准组件禁用
            hideSuccess |= hideComponentMethod1();
            
            // 通用方法2：使用反射强制隐藏
            hideSuccess |= hideComponentMethod2();
            
            // 通用方法3：多重组件禁用
            hideSuccess |= hideComponentMethod3Enhanced();
            
            // 通用方法4：反射和系统级隐藏
            hideSuccess |= hideComponentMethod4Enhanced();
            
            // 方法5：Android版本和厂商特定优化
            hideSuccess |= hideComponentMethod5AndroidSpecific();
            
            // Android 10+特殊处理
            if (sdkVersion >= 29) {
                hideSuccess |= hideForAndroid10Plus();
            }
            
            if (hideSuccess) {
                Log.i(TAG, "✅ COMPREHENSIVE_HIDE_SUCCESS - App successfully hidden using one or more methods");
                showToast("应用已成功隐藏");
            } else {
                Log.w(TAG, "⚠️ COMPREHENSIVE_HIDE_PARTIAL - Some hiding methods failed, app may still be visible");
                showToast("警告：隐藏可能不完全，请检查应用列表");
            }
            
        } catch (Exception e) {
            Log.e(TAG, "❌ ERROR_COMPREHENSIVE_HIDE", e);
            showToast("隐藏失败: " + e.getMessage());
        }
    }
    
    /**
     * 检测是否为华为设备（包括荣耀）
     */
    private boolean isHuaweiDevice(String manufacturer) {
        return manufacturer.contains("huawei") || manufacturer.contains("honor");
    }
    
    /**
     * 检测是否为三星设备
     */
    private boolean isSamsungDevice(String manufacturer) {
        return manufacturer.contains("samsung");
    }
    
    /**
     * 检测是否为小米设备
     */
    private boolean isXiaomiDevice(String manufacturer) {
        return manufacturer.contains("xiaomi") || manufacturer.contains("redmi");
    }
    
    /**
     * 检测是否为OPPO/VIVO设备
     */
    private boolean isOppoVivoDevice(String manufacturer) {
        return manufacturer.contains("oppo") || manufacturer.contains("vivo") || manufacturer.contains("oneplus");
    }
    
    /**
     * 华为/荣耀设备专用隐藏方法
     */
    private boolean hideForHuawei() {
        try {
            Log.d(TAG, "🔧 HUAWEI_HIDING - Applying Huawei-specific hiding methods");
            
            // 华为EMUI特殊处理
            ComponentName aliasComponent = new ComponentName(packageName, packageName + ".BlueAlias");
            
            // 使用华为推荐的禁用方式
            packageManager.setComponentEnabledSetting(
                    aliasComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                    PackageManager.DONT_KILL_APP | PackageManager.SYNCHRONOUS
            );
            
            // 额外的华为特定方法
            try {
                Class<?> pmClass = packageManager.getClass();
                Method hideMethod = pmClass.getDeclaredMethod(
                        "setApplicationEnabledSetting", 
                        String.class, 
                        int.class, 
                        int.class
                );
                hideMethod.setAccessible(true);
                hideMethod.invoke(packageManager, packageName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER, 0);
            } catch (Exception e) {
                Log.w(TAG, "Huawei reflection method failed: " + e.getMessage());
            }
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "❌ HUAWEI_HIDING_FAILED", e);
            return false;
        }
    }
    
    /**
     * 三星设备专用隐藏方法
     */
    private boolean hideForSamsung() {
        try {
            Log.d(TAG, "🔧 SAMSUNG_HIDING - Applying Samsung-specific hiding methods");
            
            // 三星One UI特殊处理
            ComponentName aliasComponent = new ComponentName(packageName, packageName + ".BlueAlias");
            
            // 使用三星推荐的方式
            packageManager.setComponentEnabledSetting(
                    aliasComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP
            );
            
            // 延迟再次禁用确保生效
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    try {
                        packageManager.setComponentEnabledSetting(
                                aliasComponent,
                                PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                                PackageManager.DONT_KILL_APP
                        );
                    } catch (Exception e) {
                        Log.w(TAG, "Samsung delayed hiding failed", e);
                    }
                }
            }, 1000);
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "❌ SAMSUNG_HIDING_FAILED", e);
            return false;
        }
    }
    
    /**
     * 小米设备专用隐藏方法
     */
    private boolean hideForXiaomi() {
        try {
            Log.d(TAG, "🔧 XIAOMI_HIDING - Applying Xiaomi-specific hiding methods");
            
            // 小米MIUI特殊处理
            ComponentName aliasComponent = new ComponentName(packageName, packageName + ".BlueAlias");
            ComponentName mainComponent = new ComponentName(packageName, packageName + ".MainActivity");
            
            // MIUI需要同时禁用多个组件
            packageManager.setComponentEnabledSetting(
                    aliasComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                    PackageManager.DONT_KILL_APP
            );
            
            packageManager.setComponentEnabledSetting(
                    mainComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED,
                    PackageManager.DONT_KILL_APP
            );
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "❌ XIAOMI_HIDING_FAILED", e);
            return false;
        }
    }
    
    /**
     * OPPO/VIVO设备专用隐藏方法
     */
    private boolean hideForOppoVivo() {
        try {
            Log.d(TAG, "🔧 OPPO_VIVO_HIDING - Applying OPPO/VIVO-specific hiding methods");
            
            // ColorOS/FuntouchOS特殊处理
            ComponentName aliasComponent = new ComponentName(packageName, packageName + ".BlueAlias");
            
            // 使用强制禁用模式
            packageManager.setComponentEnabledSetting(
                    aliasComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    0 // 不使用DONT_KILL_APP，让系统重启launcher
            );
            
            // 立即再次设置为USER_DISABLED
            packageManager.setComponentEnabledSetting(
                    aliasComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                    PackageManager.DONT_KILL_APP
            );
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "❌ OPPO_VIVO_HIDING_FAILED", e);
            return false;
        }
    }
    
    /**
     * Android 10+特殊处理
     */
    private boolean hideForAndroid10Plus() {
        try {
            Log.d(TAG, "🔧 ANDROID_10_PLUS_HIDING - Applying Android 10+ specific methods");
            
            // Android 10+需要特殊权限处理
            ComponentName aliasComponent = new ComponentName(packageName, packageName + ".BlueAlias");
            
            // 使用新的API方法
            packageManager.setComponentEnabledSetting(
                    aliasComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                    PackageManager.DONT_KILL_APP | PackageManager.SYNCHRONOUS
            );
            
            // 尝试使用PackageInstaller API
            try {
                android.content.pm.PackageInstaller installer = packageManager.getPackageInstaller();
                // 这里可以添加更多Android 10+特定的隐藏逻辑
            } catch (Exception e) {
                Log.w(TAG, "PackageInstaller method failed: " + e.getMessage());
            }
            
            return true;
        } catch (Exception e) {
            Log.e(TAG, "❌ ANDROID_10_PLUS_HIDING_FAILED", e);
            return false;
        }
    }
    
    /**
     * 方法1：标准组件禁用
     */
    private boolean hideComponentMethod1() {
        try {
            Log.d(TAG, "🔧 METHOD_1 - Standard component disabling");
            
            // 禁用BlueAlias
            ComponentName aliasComponent = new ComponentName(
                    packageName, 
                    packageName + ".BlueAlias"
            );
            
            packageManager.setComponentEnabledSetting(
                    aliasComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                    PackageManager.DONT_KILL_APP
            );
            
            // 验证状态
            int aliasState = packageManager.getComponentEnabledSetting(aliasComponent);
            Log.d(TAG, "Alias state: " + getStateString(aliasState));
            
            // 同时禁用MainActivity
            ComponentName mainComponent = new ComponentName(
                    packageName,
                    packageName + ".MainActivity"
            );
            
            packageManager.setComponentEnabledSetting(
                    mainComponent,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                    PackageManager.DONT_KILL_APP
            );
            
            int mainState = packageManager.getComponentEnabledSetting(mainComponent);
            Log.d(TAG, "Main state: " + getStateString(mainState));
            
            boolean success = (aliasState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER);
            Log.d(TAG, "Method 1 result: " + success);
            return success;
            
        } catch (Exception e) {
            Log.e(TAG, "❌ METHOD_1_FAILED", e);
            return false;
        }
    }
    
    /**
     * 方法2：使用反射强制隐藏
     */
    private boolean hideComponentMethod2() {
        try {
            Log.d(TAG, "🔧 METHOD_2 - Reflection-based hiding");
            
            // 尝试使用反射调用隐藏的API
            Class<?> pmClass = packageManager.getClass();
            Method setAppHiddenMethod = pmClass.getDeclaredMethod(
                    "setApplicationHiddenSettingAsUser", 
                    String.class, 
                    boolean.class, 
                    int.class
            );
            setAppHiddenMethod.setAccessible(true);
            
            // 隐藏应用
            setAppHiddenMethod.invoke(packageManager, packageName, true, 0);
            
            Log.d(TAG, "Method 2 executed successfully");
            return true;
            
        } catch (Exception e) {
            Log.w(TAG, "Method 2 failed (expected on non-system apps): " + e.getMessage());
            return false;
        }
    }
    
    /**
     * 方法3增强版：多重组件禁用
     */
    private boolean hideComponentMethod3Enhanced() {
        try {
            Log.d(TAG, "🔧 METHOD_3_ENHANCED - Multiple component disabling");
            
            boolean success = false;
            
            // 禁用所有可能的启动组件
            String[] componentSuffixes = {
                    ".BlueAlias",
                    ".TransparentAlias",
                    ".HiddenAlias",
                    ".MainActivity"
            };
            
            for (String suffix : componentSuffixes) {
                try {
                    ComponentName component = new ComponentName(packageName, packageName + suffix);
                    
                    // 先设置为DISABLED
                    packageManager.setComponentEnabledSetting(
                            component,
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                            PackageManager.DONT_KILL_APP
                    );
                    
                    // 再设置为DISABLED_USER（更强的禁用）
                    packageManager.setComponentEnabledSetting(
                            component,
                            PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                            PackageManager.DONT_KILL_APP
                    );
                    
                    int state = packageManager.getComponentEnabledSetting(component);
                    if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER || 
                        state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED) {
                        success = true;
                        Log.d(TAG, "Successfully disabled component: " + suffix);
                    }
                    
                } catch (Exception e) {
                    Log.w(TAG, "Failed to disable component " + suffix + ": " + e.getMessage());
                }
            }
            
            // 额外尝试：禁用应用的所有Activity
            try {
                android.content.pm.PackageInfo packageInfo = packageManager.getPackageInfo(
                        packageName, 
                        PackageManager.GET_ACTIVITIES
                );
                
                if (packageInfo.activities != null) {
                    for (android.content.pm.ActivityInfo activity : packageInfo.activities) {
                        if (activity.exported) { // 只禁用导出的Activity
                            ComponentName activityComponent = new ComponentName(
                                    packageName, 
                                    activity.name
                            );
                            
                            packageManager.setComponentEnabledSetting(
                                    activityComponent,
                                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                                    PackageManager.DONT_KILL_APP
                            );
                            
                            Log.d(TAG, "Disabled exported activity: " + activity.name);
                        }
                    }
                }
            } catch (Exception e) {
                Log.w(TAG, "Failed to enumerate activities: " + e.getMessage());
            }
            
            Log.d(TAG, "Method 3 Enhanced result: " + success);
            return success;
            
        } catch (Exception e) {
            Log.e(TAG, "❌ METHOD_3_ENHANCED_FAILED", e);
            return false;
        }
    }
    
    /**
     * 方法4增强版：反射和系统级隐藏
     */
    private boolean hideComponentMethod4Enhanced() {
        try {
            Log.d(TAG, "🔧 METHOD_4_ENHANCED - Reflection and system-level hiding");
            
            boolean success = false;
            
            // 尝试1：使用反射调用隐藏的API
            try {
                Class<?> pmClass = packageManager.getClass();
                Method setApplicationHiddenMethod = pmClass.getDeclaredMethod(
                        "setApplicationHiddenSettingAsUser", 
                        String.class, 
                        boolean.class, 
                        int.class
                );
                setApplicationHiddenMethod.setAccessible(true);
                
                // 尝试隐藏应用（用户ID 0 = 当前用户）
                setApplicationHiddenMethod.invoke(packageManager, packageName, true, 0);
                
                Log.d(TAG, "Reflection method 1 completed");
                success = true;
                
            } catch (Exception e) {
                Log.w(TAG, "Reflection method 1 failed: " + e.getMessage());
            }
            
            // 尝试2：使用另一个反射方法
            try {
                Class<?> pmClass = packageManager.getClass();
                Method hideMethod = pmClass.getDeclaredMethod(
                        "setComponentEnabledSetting",
                        ComponentName.class,
                        int.class,
                        int.class,
                        int.class
                );
                hideMethod.setAccessible(true);
                
                ComponentName component = new ComponentName(packageName, packageName + ".BlueAlias");
                
                // 使用额外的用户参数
                hideMethod.invoke(packageManager, component, PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER, PackageManager.DONT_KILL_APP, 0);
                
                Log.d(TAG, "Reflection method 2 completed");
                success = true;
                
            } catch (Exception e) {
                Log.w(TAG, "Reflection method 2 failed: " + e.getMessage());
            }
            
            // 尝试3：强制清除启动器缓存
            try {
                Intent intent = new Intent("android.intent.action.MAIN");
                intent.addCategory("android.intent.category.HOME");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                
                // 发送广播通知启动器更新
                Intent updateIntent = new Intent("android.intent.action.PACKAGE_CHANGED");
                updateIntent.setData(android.net.Uri.parse("package:" + packageName));
                context.sendBroadcast(updateIntent);
                
                Log.d(TAG, "Launcher cache clear attempted");
                
            } catch (Exception e) {
                Log.w(TAG, "Launcher cache clear failed: " + e.getMessage());
            }
            
            // 尝试4：使用shell命令（如果可用）
            try {
                Process process = Runtime.getRuntime().exec(new String[]{
                        "pm", "disable", packageName + "/.BlueAlias"
                });
                
                int exitCode = process.waitFor();
                if (exitCode == 0) {
                    Log.d(TAG, "Shell command succeeded");
                    success = true;
                } else {
                    Log.w(TAG, "Shell command failed with exit code: " + exitCode);
                }
                
            } catch (Exception e) {
                Log.w(TAG, "Shell command failed: " + e.getMessage());
            }
            
            Log.d(TAG, "Method 4 Enhanced result: " + success);
            return success;
            
        } catch (Exception e) {
            Log.e(TAG, "❌ METHOD_4_ENHANCED_FAILED", e);
            return false;
        }
    }
    
    /**
     * 方法5：Android版本和厂商特定优化
     */
    private boolean hideComponentMethod5AndroidSpecific() {
        try {
            Log.d(TAG, "🔧 METHOD_5_ANDROID_SPECIFIC - Android version and manufacturer specific hiding");
            
            boolean success = false;
            int sdkVersion = Build.VERSION.SDK_INT;
            String manufacturer = Build.MANUFACTURER.toLowerCase();
            
            Log.d(TAG, "Android SDK: " + sdkVersion + ", Manufacturer: " + manufacturer);
            
            // Android 10 (API 29) 特殊处理
            if (sdkVersion >= 29 && sdkVersion <= 35) {
                try {
                    // 使用新的隐藏API
                    Class<?> pmClass = packageManager.getClass();
                    
                    // 尝试调用setApplicationHiddenSettingAsUser
                    try {
                        Method hideAppMethod = pmClass.getDeclaredMethod(
                                "setApplicationHiddenSettingAsUser",
                                String.class,
                                boolean.class,
                                android.os.UserHandle.class
                        );
                        hideAppMethod.setAccessible(true);
                        
                        // 获取当前用户
                        android.os.UserHandle currentUser = android.os.Process.myUserHandle();
                        hideAppMethod.invoke(packageManager, packageName, true, currentUser);
                        
                        Log.d(TAG, "Android 10+ hiding method succeeded");
                        success = true;
                        
                    } catch (Exception e) {
                        Log.w(TAG, "Android 10+ hiding method failed: " + e.getMessage());
                    }
                    
                } catch (Exception e) {
                    Log.w(TAG, "Android 10+ specific handling failed: " + e.getMessage());
                }
            }
            
            // 华为设备特殊处理
            if (manufacturer.contains("huawei") || manufacturer.contains("honor")) {
                try {
                    Log.d(TAG, "Applying Huawei/Honor specific hiding");
                    
                    // 华为设备可能需要特殊的组件禁用方式
                    ComponentName[] components = {
                            new ComponentName(packageName, packageName + ".BlueAlias"),
                            new ComponentName(packageName, packageName + ".MainActivity")
                    };
                    
                    for (ComponentName component : components) {
                        // 华为设备使用DISABLED_UNTIL_USED可能更有效
                        packageManager.setComponentEnabledSetting(
                                component,
                                PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED,
                                PackageManager.DONT_KILL_APP
                        );
                        
                        // 再设置为完全禁用
                        packageManager.setComponentEnabledSetting(
                                component,
                                PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                                PackageManager.DONT_KILL_APP
                        );
                    }
                    
                    success = true;
                    Log.d(TAG, "Huawei/Honor specific hiding completed");
                    
                } catch (Exception e) {
                    Log.w(TAG, "Huawei/Honor specific hiding failed: " + e.getMessage());
                }
            }
            
            // 小米设备特殊处理
            if (manufacturer.contains("xiaomi") || manufacturer.contains("redmi")) {
                try {
                    Log.d(TAG, "Applying Xiaomi specific hiding");
                    
                    // 小米设备可能需要清除MIUI启动器缓存
                    Intent miuiIntent = new Intent("miui.intent.action.APP_PERM_EDITOR");
                    miuiIntent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
                    miuiIntent.putExtra("extra_pkgname", packageName);
                    
                    // 发送广播通知MIUI系统
                    Intent miuiUpdateIntent = new Intent("miui.intent.action.PACKAGE_CHANGED");
                    miuiUpdateIntent.setData(android.net.Uri.parse("package:" + packageName));
                    context.sendBroadcast(miuiUpdateIntent);
                    
                    success = true;
                    Log.d(TAG, "Xiaomi specific hiding completed");
                    
                } catch (Exception e) {
                    Log.w(TAG, "Xiaomi specific hiding failed: " + e.getMessage());
                }
            }
            
            // OPPO/Vivo设备特殊处理
            if (manufacturer.contains("oppo") || manufacturer.contains("vivo") || manufacturer.contains("oneplus")) {
                try {
                    Log.d(TAG, "Applying OPPO/Vivo/OnePlus specific hiding");
                    
                    // ColorOS/FuntouchOS可能需要特殊处理
                    ComponentName mainAlias = new ComponentName(packageName, packageName + ".BlueAlias");
                    
                    // 使用多次设置确保生效
                    for (int i = 0; i < 3; i++) {
                        packageManager.setComponentEnabledSetting(
                                mainAlias,
                                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                                PackageManager.DONT_KILL_APP
                        );
                        
                        Thread.sleep(100); // 短暂延迟
                        
                        packageManager.setComponentEnabledSetting(
                                mainAlias,
                                PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER,
                                PackageManager.DONT_KILL_APP
                        );
                    }
                    
                    success = true;
                    Log.d(TAG, "OPPO/Vivo/OnePlus specific hiding completed");
                    
                } catch (Exception e) {
                    Log.w(TAG, "OPPO/Vivo/OnePlus specific hiding failed: " + e.getMessage());
                }
            }
            
            // 三星设备特殊处理
            if (manufacturer.contains("samsung")) {
                try {
                    Log.d(TAG, "Applying Samsung specific hiding");
                    
                    // 三星设备可能需要通知TouchWiz/One UI启动器
                    Intent samsungIntent = new Intent("com.sec.android.intent.action.BADGE_COUNT_UPDATE");
                    samsungIntent.putExtra("badge_count_package_name", packageName);
                    samsungIntent.putExtra("badge_count_class_name", packageName + ".MainActivity");
                    samsungIntent.putExtra("badge_count", 0);
                    context.sendBroadcast(samsungIntent);
                    
                    // 发送包变更通知
                    Intent packageChangedIntent = new Intent(Intent.ACTION_PACKAGE_CHANGED);
                    packageChangedIntent.setData(android.net.Uri.parse("package:" + packageName));
                    context.sendBroadcast(packageChangedIntent);
                    
                    success = true;
                    Log.d(TAG, "Samsung specific hiding completed");
                    
                } catch (Exception e) {
                    Log.w(TAG, "Samsung specific hiding failed: " + e.getMessage());
                }
            }
            
            Log.d(TAG, "Method 5 Android specific result: " + success);
            return success;
            
        } catch (Exception e) {
            Log.e(TAG, "❌ METHOD_5_ANDROID_SPECIFIC_FAILED", e);
            return false;
        }
    }
    
    /**
     * 获取组件状态的字符串描述
     */
    private String getStateString(int state) {
        switch (state) {
            case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
                return "DEFAULT";
            case PackageManager.COMPONENT_ENABLED_STATE_ENABLED:
                return "ENABLED";
            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
                return "DISABLED";
            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER:
                return "DISABLED_USER";
            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED:
                return "DISABLED_UNTIL_USED";
            default:
                return "UNKNOWN(" + state + ")";
        }
    }
    
    /**
     * 显示Toast消息
     */
    private void showToast(String message) {
        try {
            if (context instanceof Activity) {
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        } catch (Exception e) {
            Log.e(TAG, "Error showing toast", e);
        }
    }
}
